package com.wanmait.spacesys.controller;

import java.io.File;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.PrintWriter;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.UUID;

import javax.servlet.ServletConfig;
import javax.servlet.ServletException;
import javax.servlet.annotation.MultipartConfig;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;
import javax.servlet.http.Part;

import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;
import com.wanmait.spacesys.dao.ConfigDAO;
import com.wanmait.spacesys.dao.ManagerinfoDAO;
import com.wanmait.spacesys.dao.PostDAO;
import com.wanmait.spacesys.vo.Config;
import com.wanmait.spacesys.vo.Managerinfo;
import com.wanmait.spacesys.vo.Photo;
import com.wanmait.spacesys.vo.Post;
import com.wanmait.spacesys.vo.PostDetail;
import com.wanmait.spacesys.vo.ReportDetail;
import com.wanmait.spacesys.vo.ReportedMan;
import com.wanmait.spacesys.vo.UserDetail;


/**
 * Servlet implementation class ManagerController
 */
@WebServlet("/ManagerController")
@MultipartConfig
public class ManagerController extends BaseController {
	private ManagerinfoDAO managerinfoDAO = new ManagerinfoDAO();
	private PostDAO postDAO = new PostDAO();
	private ConfigDAO  configDAO = new ConfigDAO();

	private void refreshConfig() {
		List<Config> configs = configDAO.findAll();
		Map<String,String> map = new HashMap<String,String>();
		for(Config config:configs) {
			map.put(config.getKey(), config.getValue());
		}
		this.getServletContext().setAttribute("configMap", map);
		this.getServletContext().setAttribute("configList", configs);
	}
	//config添加
	protected void addConfig(HttpServletRequest request, HttpServletResponse response)
			throws ServletException, IOException {
		String des = request.getParameter("des");
		String key = request.getParameter("key");
		String val = request.getParameter("val");
		configDAO.addConfig(des,key,val);
		this.refreshConfig();
	}
	//config保存
	protected void saveConfig(HttpServletRequest request, HttpServletResponse response)
			throws ServletException, IOException {
		String resultJSON = request.getParameter("r");
		JSONObject jsonObject = JSONObject.parseObject(resultJSON);
		String key =  jsonObject.getString("key");
		String val = jsonObject.getString("val");
		String idStr = jsonObject.getString("id");
		String des = jsonObject.getString("des");
		Config config = new Config();
		config.setDescription(des);
		config.setId(Integer.parseInt(idStr));
		config.setKey(key);
		config.setValue(val);
		configDAO.save(config);
		this.refreshConfig();
	}
	//config 配置删除
	protected void delConfig(HttpServletRequest request, HttpServletResponse response)
			throws ServletException, IOException {
		String idStr = request.getParameter("id");
		Integer id = Integer.parseInt(idStr);
		configDAO.delConfig(id);
		this.refreshConfig();
	}
	//文章内容详情
	protected void postContent(HttpServletRequest request, HttpServletResponse response)
			throws ServletException, IOException {
		String postIdStr = request.getParameter("postId");
		Integer postId = Integer.parseInt(postIdStr);
		Post post = postDAO.findById(postId);
		request.setAttribute("post", post);
		this.forward("/web/manager/postContentDetail.jsp", request, response);
		
	}
	//管理员 删除评论 1.举报次数清零  2.ischeck=1
	protected void deleteComment(HttpServletRequest request, HttpServletResponse response)
			throws ServletException, IOException {
		String idStr = request.getParameter("id");
		Integer id = Integer.parseInt(idStr);
		String commentIdStr = request.getParameter("commentId");
		String[] strArray = null;   
        strArray = commentIdStr.split(",");
		int [] num=new int[strArray.length];
		for(int i=0;i<num.length;i++){
			num[i]=Integer.parseInt(strArray[i]);
		}
		managerinfoDAO.deleteComment(num,id);
	}
	//管理员禁言用户操作 1.举报次数清零  2.ischeck=1
	protected void spack(HttpServletRequest request, HttpServletResponse response)
			throws ServletException, IOException {
		String idStr = request.getParameter("id");
		Integer id = Integer.parseInt(idStr);
		String timeStr = request.getParameter("time");
		Integer time = Integer.parseInt(timeStr);
		Managerinfo managerinfo = (Managerinfo)request.getSession().getAttribute("Managerinfo");
		Integer managerId = managerinfo.getId();
		managerinfoDAO.sapck(id,managerId,time);
	}
	//管理员拉黑用户 1.举报次数清零  2.ischeck=1
	protected void black(HttpServletRequest request, HttpServletResponse response)
			throws ServletException, IOException {
		String idStr = request.getParameter("id");
		Integer id = Integer.parseInt(idStr);
		managerinfoDAO.black(id);
	}
	//忽略掉举报 1.举报次数清零  2.ischeck=1
	protected void ignore(HttpServletRequest request, HttpServletResponse response)
			throws ServletException, IOException {
		String idStr = request.getParameter("id");
		Integer id = Integer.parseInt(idStr);
		//举报次数清零
		managerinfoDAO.clearCount(id);
		//举报列表  ischeck=1;
		managerinfoDAO.updateIsCheck(id);
	}
	//被举报人详情列表
	protected void reportDetail(HttpServletRequest request, HttpServletResponse response)
			throws ServletException, IOException {
		String idStr = request.getParameter("userinfoId");
		Integer id = Integer.parseInt(idStr);
		List<ReportedMan> reports = managerinfoDAO.reportDetail(id);
		String username =  managerinfoDAO.findById(id);
		List<Integer>countComment=managerinfoDAO.countComment(id);
		request.setAttribute("reports", reports);
		request.setAttribute("userinfoId", id);
		request.setAttribute("username", username);
		request.setAttribute("countComment", countComment);
		this.forward("/web/manager/reportDetail.jsp", request, response);
		
	}
	//查找举报列表
	protected void reportList(HttpServletRequest request, HttpServletResponse response)
			throws ServletException, IOException {
		List<ReportDetail> reports = managerinfoDAO.reportList();
		request.setAttribute("reports", reports);
		this.forward("/web/manager/reportAjax.jsp", request, response);
	}
	//计算举报列表的数量
	protected void pageNumberReport(HttpServletRequest request, HttpServletResponse response)
			throws ServletException, IOException {
		int count = managerinfoDAO.pageNumberReport();
//		System.out.println(count);
		response.getWriter().print(count);
	}
	
	//计算已审核的页码
	protected void pageNumberPass(HttpServletRequest request, HttpServletResponse response)
			throws ServletException, IOException {
		int count = managerinfoDAO.pageNumberPass();
		response.getWriter().print(count);
	}
	
	//切换到 已审核列表，查找已审核的帖子
	protected void passList(HttpServletRequest request, HttpServletResponse response)
			throws ServletException, IOException {
		List<PostDetail> passes = new ArrayList<>();
		passes = managerinfoDAO.passList(Integer.parseInt(request.getParameter("pageNum")),this.countPage(request, response));
		request.setAttribute("passes", passes);
		this.forward("/web/manager/checkedAjax.jsp", request, response);
	}
	
	//执行点击 审核帖子
	protected void clickNoPass(HttpServletRequest request, HttpServletResponse response)
			throws ServletException, IOException {
		managerinfoDAO.clickNoPass(Integer.parseInt(request.getParameter("postId")));
	}
	protected void clickPass(HttpServletRequest request, HttpServletResponse response)
			throws ServletException, IOException {
		managerinfoDAO.clickPass(Integer.parseInt(request.getParameter("postId")));
	}
	
	//未审核的帖子数量
	protected void pageNumberNoPass(HttpServletRequest request, HttpServletResponse response)
			throws ServletException, IOException {
		int count = managerinfoDAO.pageNumberNoPass();
		response.getWriter().print(count);
	}
	//查找出未审核的帖子
	protected void noPass(HttpServletRequest request, HttpServletResponse response)
			throws ServletException, IOException {
		List<PostDetail> noPasses = new ArrayList<>();
		noPasses = managerinfoDAO.noPass();
		request.setAttribute("noPasses", noPasses);
		this.forward("/web/manager/check-passAjax.jsp", request, response);
	}
	//ajax 获取所有用户列表 ，默认第一页
	protected void userList(HttpServletRequest request, HttpServletResponse response)
			throws ServletException, IOException {
		Integer pageNum = Integer.parseInt(request.getParameter("pageNum"));
		response.setCharacterEncoding("utf-8");
		response.setContentType("application/json;charset=utf-8");
		List<UserDetail>users =  managerinfoDAO.userList(pageNum,this.countPage(request, response));
		this.countPage(request, response);
		request.setAttribute("users", users);
		this.forward("/web/manager/listAjax.jsp", request, response);
		
	}
	// ajax获取 黑名单用户列表 。默认第一页
	protected void blackList(HttpServletRequest request, HttpServletResponse response)
			throws ServletException, IOException {
		Integer pageNum = Integer.parseInt(request.getParameter("pageNum"));
		response.setCharacterEncoding("utf-8");
		response.setContentType("application/json;charset=utf-8");
		List<UserDetail>users =  managerinfoDAO.blackList(pageNum,this.countPage(request, response));
		request.setAttribute("users", users);
		this.forward("/web/manager/listAjax.jsp", request, response);
	}
	protected void spackList(HttpServletRequest request, HttpServletResponse response)
			throws ServletException, IOException {
		
		Integer pageNum = Integer.parseInt(request.getParameter("pageNum"));
		response.setCharacterEncoding("utf-8");
		response.setContentType("application/json;charset=utf-8");
		List<UserDetail>users =  managerinfoDAO.spackList(pageNum,this.countPage(request, response));
		request.setAttribute("users", users);
		this.forward("/web/manager/listAjax.jsp", request, response);
	}
	//获取application里面的页码
	protected int countPage(HttpServletRequest request, HttpServletResponse response) {
		HashMap<String,String> map = (HashMap<String,String>)request.getServletContext().getAttribute("configMap");
		String pageCountStr = map.get("page_size");
		int pageCount = Integer.parseInt(pageCountStr);
		return pageCount;
	}
	
	//ajax 获取 四种数量：禁言 拉黑用户  所有用户  帖子数量
	protected void countNum(HttpServletRequest request, HttpServletResponse response)
			throws ServletException, IOException {
		response.setCharacterEncoding("utf-8");
		response.setContentType("application/json;charset=utf-8");
		int spack = this.findAllOfSpack(request, response);
		int black = this.findAllOfBlack(request, response);
		int user = this.findAllUserNumber(request, response);
		int post = this.findAllPost(request, response);
		Map <String,Integer> countMap =new HashMap<>();
		countMap.put("spack",spack );
		countMap.put("black",black );
		countMap.put("user",user);
		countMap.put("post",post);
		JSONArray.writeJSONString(response.getWriter(),countMap);
	}
	protected void pageNumber(HttpServletRequest request, HttpServletResponse response)
			throws ServletException, IOException {
		int pageNum = this.findAllUserNumber(request, response);
		response.getWriter().print(pageNum);
	}
	
	protected void pageNumberBlack(HttpServletRequest request, HttpServletResponse response)
			throws ServletException, IOException {
		int pageNum = this.findAllOfBlack(request, response);
		response.getWriter().print(pageNum);
	}
	protected void pageNumberSpack(HttpServletRequest request, HttpServletResponse response)
			throws ServletException, IOException {
		int pageNum = this.findAllOfSpack(request, response);
		response.getWriter().print(pageNum);
	}
	//查找禁言用户的数量
	protected int findAllOfSpack(HttpServletRequest request, HttpServletResponse response)
			throws ServletException, IOException {
		return managerinfoDAO.findAllOfSpack();
	}
	//查找拉黑用户的数量
	protected int findAllOfBlack(HttpServletRequest request, HttpServletResponse response)
			throws ServletException, IOException {
		return managerinfoDAO.findAllOfBlack();
	}
	//查找所有用户数量
	protected int findAllUserNumber(HttpServletRequest request, HttpServletResponse response)
			throws ServletException, IOException {
		return managerinfoDAO.findAllUserNumber();
	}
	//查找发帖子数量
	protected int findAllPost(HttpServletRequest request, HttpServletResponse response)
			throws ServletException, IOException {
		return managerinfoDAO.findAllPost();
	}
	//修改密码
	protected void changePass(HttpServletRequest request, HttpServletResponse response)
			throws ServletException, IOException {
		String newPass = request.getParameter("newPass");
		//获取管理者的session
		HttpSession session = request.getSession();
		Managerinfo managerinfo = (Managerinfo)session.getAttribute("Managerinfo");
		Integer id = managerinfo.getId();
		managerinfoDAO.changePass(id,newPass);
		session.setAttribute("Managerinfo", null);
		this.redirect("/web/manager/managerLogin.jsp", request, response);
	}
	//修改密码前核实原密码：
	protected void checkPrePass(HttpServletRequest request, HttpServletResponse response)
			throws ServletException, IOException {
		String prePass=request.getParameter("prePass");
		HttpSession session = request.getSession();
		Managerinfo managerinfo = (Managerinfo)session.getAttribute("Managerinfo");
		Integer id = managerinfo.getId();
		int flag = managerinfoDAO.checkPrePass(prePass,id);
		response.getWriter().print(flag);
		
	}
	//上传图集
	protected void uploadPhoto(HttpServletRequest request, HttpServletResponse response)
			throws ServletException, IOException {
		Part part = request.getPart("loadPic");
		String fileName = this.savePicture(part, request, response);
		Photo photo = new Photo();
		Managerinfo managerinfo = (Managerinfo)request.getSession().getAttribute("Managerinfo");
		photo.setManagerId(managerinfo.getId());
		photo.setPic(fileName);
		int bingo = managerinfoDAO.uploadPhoto(photo);
		this.redirect("/web/manager/load-pic.jsp?bingo="+bingo, request, response);
	}
	public String savePicture(Part part,HttpServletRequest request, HttpServletResponse response)throws ServletException, IOException {
		String name = part.getSubmittedFileName();
		String ext = name.substring(name.lastIndexOf('.'));
		String fileName = UUID.randomUUID().toString()+ext;
		InputStream is = part.getInputStream();
		String realPath = this.getServletContext().getRealPath("/images/indexImages");
		File dir = new File(realPath);
		if(!dir.exists()) {
			dir.mkdirs();
		}
		File file = new File(dir,fileName);
		FileOutputStream fos = new FileOutputStream(file);
		byte[] buf = new byte[1024*8];
		int len = 0;
		while(true) {
			len = is.read(buf);
			if(len==-1) break;
			fos.write(buf,0,len);
		}
		fos.close();
		is.close();
		return fileName;
	}
	
	//管理员登录
//	protected void Login(HttpServletRequest request, HttpServletResponse response)throws ServletException, IOException {
//		String username =  request.getParameter("username");
//		String password =  request.getParameter("password");
//		Managerinfo managerinfo =  managerinfoDAO.isExist(username, password);
//		request.getSession().setAttribute("Managerinfo", managerinfo);
//		if(managerinfo!=null) {
//			request.getRequestDispatcher("/web/manager/index.jsp").forward(request, response);
//		}
//	}
	
	
	//ajax判断管理员的账号密码是否正确
	protected void toLogin(HttpServletRequest request, HttpServletResponse response)throws ServletException, IOException {
		 String account =  request.getParameter("account");
		 String password = request.getParameter("password");
		 Managerinfo managerinfo =  managerinfoDAO.isExist(account, password);
		 PrintWriter out = response.getWriter();
		 if(managerinfo!=null) {
			 request.getSession().setAttribute("Managerinfo", managerinfo);
			 out.print("have");
		 }
		 else {
			 out.print("nohave");
		 }
	}
	@Override
	protected void doDefault(HttpServletRequest request, HttpServletResponse response)
			throws ServletException, IOException {
		
	}


}
